//
//  TTShopDetailViewController.m
//  TaoTuo
//
//  Created by admin on 2020/2/20.
//  Copyright © 2020 admin. All rights reserved.
//

#import "TTGoodsDetailViewController.h"
#import "TTDetailModel.h"
#import "TTDetailHeaderView.h"
#import "TTDetailInfoViewCell.h"
#import "TTDetailSectionLabel.h"
#import "TTSpecificationViewCell.h"
#import "TTDiamondModel.h"
#import "TTDiamondViewCell.h"
#import "TTCommondDataModel.h"
#import "YBImageBrowser.h"
#import "TTHomeListModel.h"
#import "TTHomeListTableViewCell.h"
#import "TTDetailImageModel.h"
#import "TTDetailImageViewCell.h"
#import "TTShopCartView.h"
#import "TTDetailStockListModel.h"
#import "LLTransition.h"
#import "TTDetailFilterViewController.h"
#import "TTShopCartViewController.h"
#import <UIImageView+WebCache.h>
#import "TTUserModel.h"
#import "TTCommitOrderViewController.h"
#import "TTDiamondsRecommendModel.h"
#import "AppDelegate.h"
#import "TTDetailShareViewController.h"
#import "TTDianpuShareView.h"
#import "TTDetailShareModel.h"
#import "TTSizeGuideViewController.h"
#import "TTPairDetailFilterViewController.h"
#import "TTMessageViewController.h"

#import "TTCustomConditionModel.h"

#import "TTExistGoodsChooseView.h"


#import "TTXianhuoModel.h"

#import "LLScreenView.h"

#define cellTye @"cellType"
#define data @"data"

static NSInteger xianhuoTag = 10000;
static NSInteger dingzhiTag = 10001;

static NSUInteger PresentFilterViewActionDefault = 999;

typedef enum : NSUInteger {
    PresentFilterViewActionWithAddCart = 1, // 加入购物车
    PresentFilterViewActionWithBuy,     // 购买
} PresentFilterViewAction;

typedef enum : NSUInteger {
    cellTypeWithInfo = 1,
    cellTypeWithGuiGe,
    cellTypeWithShiTou,
    cellTypeWithSimilar,
    cellTypeWithImages,
} cellType;

//static NSString *detailInfoCellID = @"detail_info_cell_id";
//static NSString *detailSecificationCellID = @"detail_secification_cell_id";
//static NSString *detailDiamondCellID = @"detail_diamond_cell_id";
//static NSString *detailSimilarCellID = @"detail_similar_cell_id";
static NSString *detailImagesCellID = @"detail_images_cell_id";

@interface TTGoodsDetailViewController ()<UITableViewDelegate, UITableViewDataSource, TTDiamondViewCellDelegate, MGSwipeTableCellDelegate>

@property (nonatomic, strong) UIView *navBarView;
@property (nonatomic, strong) TTDetailHeaderView *headerView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) TTDetailModel *model;
//@property (nonatomic, strong) UIImage *shadowImage;
@property (nonatomic, strong) UIView *bottomView;   // 底部view
@property (nonatomic, strong) TTShopCartView *shopCartView; // 购物车

@property (nonatomic, strong) TTHomeListModel *homeModel;
//@property (nonatomic, strong) TTXianhuoModel *xianhuoModel; //现货

//@property (nonatomic, strong) UILabel *guigeFooterLabel;    // 规格区的footerlabel

//@property (nonatomic, assign) BOOL isOpen;
//@property (nonatomic, assign) int diamondCount;     // 裸石个数

//@property (nonatomic, strong) NSMutableArray *guigeArray;   // 规格数据
//@property (nonatomic, strong) NSMutableArray *canShowGuigeArray;   // 能够展示出来的规格
//@property (nonatomic, strong) NSMutableArray *canShowShitouArray;   // 能够展示出来的裸石
//@property (nonatomic, strong) NSMutableArray *selectLuoshiArray;   // 选中的裸石数据

@property (nonatomic, strong) LLTransition *transition;

//@property (nonatomic, strong) UIView *loadingShitouView;    // 加载石头的过程添加菊花的view

@property (nonatomic, assign) BOOL imageIsOpen;  // 查看更多图片
@property (nonatomic, assign) PresentFilterViewAction presentFilterViewAction;
//@property (nonatomic, strong) UIButton *moreInfoBtn;    // 更多库存
//@property (nonatomic, assign) BOOL showAllShitou;   // 显示10条石头数据，否则显示2条
//
//@property (nonatomic, strong) UIActivityIndicatorView *indicatorView;

@property (nonatomic, strong) UIButton *addCartBtn;
@property (nonatomic, strong) UIButton *buyBtn;
@property (nonatomic, strong) UIButton *startCustomBtn;
///是否点击的定制
//@property (nonatomic, assign) BOOL isClickDingzhi;

/// 定制的view
@property (nonatomic, strong) LLScreenView *customView;

/// 定制条件
@property (nonatomic, strong) TTCustomConditionModel *customConditionModel;
/// 现货选择
@property (nonatomic, strong) TTExistGoodsChooseView *existChooseView;

/// 已售罄view
@property (nonatomic, strong) UIView *selloutView;

@end

@implementation TTGoodsDetailViewController

- (instancetype)initWithStyleLibraryId:(NSString *)styleLibraryId model:(TTHomeListModel *)homeModel
{
    self = [super init];
    if (self) {
        self.homeModel = homeModel;
        self.styleLibraryId = styleLibraryId;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    _shopCartView.count = [TTLoginSingle sharedSingle].shopCartCount;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    CGFloat alpha = self.tableView.contentOffset.y / self.view.width;
    alpha = alpha >= 1 ? 1 : alpha;
    self.navigationController.navigationBar.alpha = alpha;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.headerView.canRotation = NO;
    [self.headerView.subject sendNext:@(NO)];
    self.navigationController.navigationBar.alpha = 1;
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
    [self.headerView.playerView pause];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"商品详情";
    //设置为向上延展，不设置的话，当导航栏变为不透明的时候，页面会向下偏移
    self.edgesForExtendedLayout = UIRectEdgeTop;
    self.view.backgroundColor = RGBCOLOR(242, 245, 246);
    self.transition = [[LLTransition alloc] init];
    self.presentFilterViewAction = PresentFilterViewActionDefault; // 设置默认值
    
    [self navBarView];
    
    [self getNetworkDataSuccessBlock:nil];
    
    // 登录成功
    @weakify(self)
    [[TTLoginSingle sharedSingle].loginSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        if ([x intValue] == 1) {
            // 购物车
            self.shopCartView.count = [TTLoginSingle sharedSingle].shopCartCount;
        }
    }];
    
    // 如果是从详情进入购物车，在购物车页面删除了数据，要刷新一下页面
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNetworkDatas) name:@"shopcartdeletedata" object:nil];
    
    UIImage *image = [[UIImage imageNamed:@"detailshare"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:image style:UIBarButtonItemStyleDone target:self action:@selector(shareAction)];
    
    /// 点击了现货或定制的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickExistingOrCustomGoodsAction) name:@"clickExistingOrCustomGoodsNotify_key" object:nil];
    
}

- (void)clickExistingOrCustomGoodsAction
{
    if (self.model.isCustomGoods) {
        // 定制
        [self startCustomBtnClick];
    } else if (self.model.isExistingGoods) {
        // 现货
        [self showExistView];
    }
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat alpha = scrollView.contentOffset.y / self.view.width;
    alpha = alpha >= 1 ? 1 : alpha;
    self.navigationController.navigationBar.alpha = alpha;
    self.navBarView.alpha = 1 - alpha;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    //如果向下偏移了，再偏移回去，否则顶部状态栏会出现空白
    if (offsetY < -kStatusBarHeight) {
        [self.tableView setContentOffset:CGPointMake(0, -kStatusBarHeight) animated:YES];
    }
}

// 点击状态栏回到了顶部
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView
{
    CGFloat offsetY = scrollView.contentOffset.y;
    //如果向下偏移了，再偏移回去，否则顶部状态栏会出现空白
    if (offsetY < -kStatusBarHeight) {
        [self.tableView setContentOffset:CGPointMake(0, -kStatusBarHeight) animated:YES];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSArray *arr = dic[data];
//    if ([dic[cellTye] integerValue] == cellTypeWithInfo) {
//        return self.isOpen ? arr.count : (arr.count > 2 ? 2 : arr.count);
//    } else if ([dic[cellTye] integerValue] == cellTypeWithImages) {
//        return self.imageIsOpen ? arr.count : arr.count - 1;
//    } else if ([dic[cellTye] integerValue] == cellTypeWithShiTou) {
//        return self.showAllShitou ? arr.count : (arr.count > 2 ? 2 : arr.count);
//    }
//    return arr.count;
    if ([dic[cellTye] integerValue] == cellTypeWithImages) {
        return self.imageIsOpen ? arr.count : arr.count - 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    NSArray *arr = dic[data];
//    if ([dic[cellTye] integerValue] == cellTypeWithInfo) {
//
//        TTDetailInfoViewCell *cell = [tableView dequeueReusableCellWithIdentifier:detailInfoCellID];
//        cell.dic = arr[indexPath.row];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        return cell;
//    } else if ([dic[cellTye] integerValue] == cellTypeWithGuiGe){
//
//        TTSpecificationViewCell *cell = [tableView dequeueReusableCellWithIdentifier:detailSecificationCellID];
//        [cell setModel:arr[indexPath.row] specificationCellType:CellTypeWithSpecificationResult categoryName:self.model.CategoryName];
//        cell.delegate = self;
//        cell.rightButtons = @[[MGSwipeButton buttonWithTitle:@"删除" backgroundColor:[UIColor redColor]]];
//        cell.rightSwipeSettings.transition = MGSwipeStateSwipingLeftToRight;
//        MGSwipeSettings *setting = [[MGSwipeSettings alloc] init];
//        setting.transition = MGSwipeTransitionBorder;
//        setting.topMargin = 5;
//        setting.bottomMargin = 5;
//        cell.rightSwipeSettings = setting;
//        return cell;
//
//    } else if ([dic[cellTye] integerValue] == cellTypeWithShiTou){
//
//        TTDiamondViewCell *cell = [tableView dequeueReusableCellWithIdentifier:detailDiamondCellID];
//        [cell setModel:arr[indexPath.row] clarityCharacteristicsDic:[TTCommondDataModel getClarityCharacteristics] toTimeDic:[TTCommondDataModel toShenZhenTime] findShapeImageDic:[TTCommondDataModel findShapeImageName] cellType:CllTypeWithCanChoose showDiscount:NO];
//        cell.delegate = self;
//        return cell;
//
//    } else if ([dic[cellTye] integerValue] == cellTypeWithSimilar){
//
//        TTHomeListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:detailSimilarCellID];
//        cell.model = arr[indexPath.row];
//        return cell;
//    } else
    if ([dic[cellTye] integerValue] == cellTypeWithImages){
        TTDetailImageModel *imageModel = arr[indexPath.row];
        TTDetailImageViewCell *cell = [tableView dequeueReusableCellWithIdentifier:detailImagesCellID];
        if (imageModel.image) {
            cell.pictureView.image = imageModel.image;
        } else {
            [cell.pictureView sd_setImageWithURL:[NSURL URLWithString:imageModel.imageUrlStr] placeholderImage:[UIImage imageNamed:@"f_placeholder_img"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (image != nil) {
                    CGSize imageSize = image.size;
                    imageModel.imageHeight = imageSize.height * SCREEN_WIDTH / imageSize.width;
                    NSIndexPath *ip = [NSIndexPath indexPathForRow:indexPath.row inSection:self.dataArray.count - 1];
                    [self.tableView beginUpdates];
                    [self.tableView reloadRowsAtIndexPaths:@[ip] withRowAnimation:UITableViewRowAnimationFade];
                    [self.tableView endUpdates];
                }
            }];
        }
        
        return cell;
        
    } else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.textLabel.text = @"";
        return cell;
    }
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    NSInteger type = [dic[cellTye] integerValue];
//    if (type == cellTypeWithGuiGe){
//        self.presentFilterViewAction = PresentFilterViewActionDefault; // 设置默认值
//        [self presentFilterViewController];
//    } else if (type == cellTypeWithSimilar) {
//        TTHomeListModel *model = dic[data][indexPath.row];
//        TTGoodsDetailViewController *detailVC = [[TTGoodsDetailViewController alloc] initWithStyleLibraryId:model.StyleLibraryId model:model];
//        [self.navigationController pushViewController:detailVC animated:YES];
//    } else
    if (type == cellTypeWithImages) {
        TTDetailImageModel *model = dic[data][indexPath.row];
        if (model.imageUrlStr.length == 0) {
            return; //本地图片不用浏览
        }
        @autoreleasepool {
            NSMutableArray *imgs = [NSMutableArray array];
            for (TTDetailImageModel *model in dic[data]) {
                if (model.imageUrlStr.length > 0) {
                    YBIBImageData *imageData = [YBIBImageData new];
                    imageData.imageURL = [NSURL URLWithString:model.imageUrlStr];
                    [imgs addObject:imageData];
                }
            }
            YBImageBrowser *browser = [YBImageBrowser new];
            browser.dataSourceArray = imgs;
            browser.currentPage = indexPath.row;
            [browser show];
        }
        
    }
    
}

//#pragma mark - MGSwipeTableCellDelegate
//- (BOOL)swipeTableCell:(MGSwipeTableCell *)cell canSwipe:(MGSwipeDirection)direction fromPoint:(CGPoint)point
//{
//    return YES;
//}
//
//- (BOOL)swipeTableCell:(MGSwipeTableCell *)cell tappedButtonAtIndex:(NSInteger)index direction:(MGSwipeDirection)direction fromExpansion:(BOOL)fromExpansion
//{
//    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
//
//    TTDetailStockListModel *model = self.guigeArray[indexPath.row];
//    model.selected = NO;
//    [self.guigeArray removeObject:model];
//    [self.tableView reloadData];
//    //TODO: 请求裸石数据
//    [self afterSelectStyleGetLuoShiData];
//
//    return YES;
//}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    NSInteger typeCell = [dic[cellTye] integerValue];
//    if (typeCell == cellTypeWithInfo) {
//        return 25;
//    } else if (typeCell == cellTypeWithGuiGe){
//        TTDetailStockListModel *model = dic[data][indexPath.row];
//        CGFloat h = [tableView fd_heightForCellWithIdentifier:detailSecificationCellID cacheByIndexPath:indexPath configuration:^(TTSpecificationViewCell *cell) {
//            [cell setModel:model specificationCellType:CellTypeWithSpecificationResult categoryName:self.model.CategoryName];
//        }];
//        h = model.StockType == 2 ? h + 40 : h;
//        return h;
//    } else if (typeCell == cellTypeWithSimilar) {
//
//        TTHomeListModel *model = dic[data][indexPath.row];
//
//        NSArray *contentArray = model.DescriptionList;
//        CGFloat h = ceil(contentArray.count / 2.0) * 22 + 94;
//        h = h < 145 ? 145 : h;
//        return h * kScale + 20;
//
//    } else
    if (typeCell == cellTypeWithImages){
        TTDetailImageModel *imageModel = dic[data][indexPath.row];
        NSLog(@"高度 >>>> %f", imageModel.imageHeight);
        return imageModel.imageHeight > 0 ? imageModel.imageHeight : self.view.width;
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
//    NSDictionary *dic = self.dataArray[section];
//    NSInteger typeCell = [dic[cellTye] integerValue];
//    if (typeCell == cellTypeWithInfo) {
//        return 0;
//    }
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSInteger typeCell = [dic[cellTye] integerValue];
//    if (typeCell == cellTypeWithInfo) {
//        return self.isOpen ? 60 : 35;
//    } else if (typeCell == cellTypeWithGuiGe){
//        NSArray *arr = dic[data];
////        return arr.count > 0 ? 80 : 200;
//        return arr.count > 0 ? 50 : 170;
//    } else if (typeCell == cellTypeWithShiTou){
//        return self.showAllShitou ? 0 : 44;
//    }  else
    if (typeCell == cellTypeWithImages) {
        if (self.imageIsOpen) {
            return 0.1;
        }
        return 40;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
    NSInteger typeCell = [dic[cellTye] integerValue];
//    if (typeCell == cellTypeWithGuiGe) {
//
//        UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
//        view.backgroundColor = [UIColor whiteColor];
//        UIButton *xhBtn = [UIButton createButtonWithTitle:@"现货" titleColor:UIColorHex(333333) titleFont:[UIFont systemFontOfSize:14] backgroundColor:nil target:self action:@selector(clickMoreKuCunBtn:)];
//        xhBtn.tag = xianhuoTag;
//        [view addSubview:xhBtn];
//        [xhBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerY.equalTo(view);
//            make.left.equalTo(view);
//            make.right.equalTo(view.mas_centerX);
//        }];
//        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(self.view.width/4 - 25, 30, 50, 4)];
//        lineView.backgroundColor = kMainColor;
//        lineView.layer.cornerRadius = 2;
//        [view addSubview:lineView];
//
//        UIButton *dzBtn = [UIButton createButtonWithTitle:@"定制" titleColor:UIColorHex(333333) titleFont:[UIFont systemFontOfSize:14] backgroundColor:nil target:self action:@selector(clickMoreKuCunBtn:)];
//        dzBtn.tag = dingzhiTag;
//        [view addSubview:dzBtn];
//        [dzBtn mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.centerY.equalTo(xhBtn);
//            make.right.equalTo(view);
//            make.left.equalTo(view.mas_centerX);
//        }];
//
//        return view;
//    } else if (typeCell == cellTypeWithShiTou) {
//
//        UIView *view =[[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
//        TTDetailSectionLabel *label = [[TTDetailSectionLabel alloc] initWithFrame:CGRectMake(10, 0, 100, view.height) title:@"该托可以镶嵌的石头"];
//        [view addSubview:label];
//
//        int shitouCount = self.canShowShitouArray.count == 0 ? 0 : self.diamondCount;
//        NSString *str = [NSString stringWithFormat:@"共%d粒", shitouCount];
//        UILabel *countLabel = [UILabel labelWithTitle:str color:kMainColor fontSize:11];
//        countLabel.frame = CGRectMake(label.right, label.top, 120, view.height);
//        [view addSubview:countLabel];
//
//        UIButton *btn = [UIButton createButtonWithFrame:CGRectMake(view.width - 120, label.top, 110, 40) image:[UIImage imageNamed:@"btn_right_arrow"] title:@"根据托找个钻" titleColor:UIColorHex(666666) titleFont:[UIFont systemFontOfSize:12] space:0 backgroundColor:nil target:self action:@selector(clickFindZuanBtn)];
//        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//        [view addSubview:btn];
//
//        return view;
//    } else
    if (typeCell == cellTypeWithImages) {
        NSString *str = @"———— 商品详情 ————";
        UILabel *label = [UILabel labelTextCenterWithTitle:str color:UIColorHex(B7B7B7) fontSize:13];
        label.frame = CGRectMake(0, 0, self.view.width, 40);
        label.backgroundColor = UIColorHex(#F5F5F5);
        return label;
    }
    return [UIView new];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    NSDictionary *dic = self.dataArray[section];
//    if ([dic[cellTye] integerValue] == cellTypeWithInfo) {
//        if (self.isOpen) {
//            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 65)];
//            UILabel *label = [UILabel labelTextCenterWithTitle:@"*请以收到实物为准*" color:UIColorHex(FF1F1F) fontSize:11];
//            label.frame = CGRectMake(0, 0, self.view.width, 30);
//            [view addSubview:label];
//            UIButton *moreBtn = [UIButton createButtonWithNormalImage:[UIImage imageNamed:@"down"] selectedImage:[UIImage imageNamed:@"up"] target:self action:@selector(lookMoreInfo:)];
//            moreBtn.selected = self.isOpen;
//            moreBtn.frame = CGRectMake(0, label.bottom - 5, self.view.width, 25);
//            moreBtn.imageView.contentMode = UIViewContentModeCenter;
//            [view addSubview:moreBtn];
//            [LLLineUtilies addLineInView:view startPoint:CGPointMake(0, 55) endPoint:CGPointMake(view.width, 55) lineColor:kSeparatorColor lineWidth:10];
//            return view;
//        } else {
//            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
//            view.backgroundColor = [UIColor whiteColor];
//            UIButton *moreBtn = [UIButton createButtonWithNormalImage:[UIImage imageNamed:@"down"] selectedImage:[UIImage imageNamed:@"up"] target:self action:@selector(lookMoreInfo:)];
//            moreBtn.selected = self.isOpen;
//            moreBtn.frame = CGRectMake(0, 0, self.view.width, 25);
//            moreBtn.imageView.contentMode = UIViewContentModeCenter;
//            [view addSubview:moreBtn];
//            [LLLineUtilies addLineInView:view startPoint:CGPointMake(0, 30) endPoint:CGPointMake(view.width, 30) lineColor:kSeparatorColor lineWidth:10];
//            return view;
//        }
//    } else if ([dic[cellTye] integerValue] == cellTypeWithGuiGe) {
//        NSArray *arr = dic[data];
////        CGFloat viewH = arr.count > 0 ? 80 : 200;
//        CGFloat viewH = arr.count > 0 ? 50 : 170;
//        CGFloat hintH = arr.count > 0 ? 0 : 120;
//
//        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, viewH)];
//        UILabel *hintLabel = [UILabel labelTextCenterWithTitle:@"没有任何款式" color:UIColorHex(666666) fontSize:15];
//        hintLabel.frame = CGRectMake(0, 0, self.view.width, hintH);
//        [view addSubview:hintLabel];
//        [hintLabel addSubview:self.indicatorView];
//        self.indicatorView.center = hintLabel.center;
//        if (arr.count == 0) {
//            [LLLineUtilies addLineInView:view startPoint:CGPointZero endPoint:CGPointMake(view.width, 0) lineColor:UIColorHex(f2f2f2)];
//        }
//        [LLLineUtilies addLineInView:view startPoint:CGPointMake(0, hintH) endPoint:CGPointMake(view.width, hintH) lineColor:UIColorHex(f2f2f2)];
//
//        NSInteger count = 0;
//        for (TTDetailStockListModel *lm in self.guigeArray) {
//            count += (lm.buyCount == 0 ? 1 : lm.buyCount);
//        }
//        NSString *countStr = [NSString stringWithFormat:@"已选规格(%ld件)", count];
//        UILabel *countLabel = [UILabel labelWithTitle:countStr color:UIColorHex(333333) fontSize:14];
//        countLabel.frame = CGRectMake(10, hintH, 150, 30);
//        [view addSubview:countLabel];
//
//        UIButton *chicunBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"尺寸指南"];
//        [attr addAttributes:@{NSForegroundColorAttributeName : UIColorHex(999999), NSFontAttributeName : [UIFont systemFontOfSize:11], NSUnderlineStyleAttributeName : @1} range:NSMakeRange(0, attr.string.length)];
//        [chicunBtn setAttributedTitle:attr forState:UIControlStateNormal];
//        [chicunBtn addTarget:self action:@selector(lookChicunGuide) forControlEvents:UIControlEventTouchUpInside];
//        chicunBtn.frame = CGRectMake(self.view.width - 100, hintH, 90, 30);
//        chicunBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
//        [view addSubview:chicunBtn];
//
//        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, countLabel.bottom, self.view.width, 10)];
//        lineView.backgroundColor = kSeparatorColor;
//        [view addSubview:lineView];
//
//        return view;
//    } else if ([dic[cellTye] integerValue] == cellTypeWithShiTou) {
//        int shitouCount = self.canShowShitouArray.count == 0 ? 0 : self.diamondCount;
//        if (self.showAllShitou || shitouCount == 0) {
//            return [UIView new];
//        }
//        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 44)];
//        view.backgroundColor = [UIColor whiteColor];
//
//        UIButton *btn = [UIButton createButtonWithFrame:CGRectMake(self.view.width * 0.5 - 80, 0, 160, 34) image:[UIImage imageNamed:@"down_arrow"] title:@"展开更多" titleColor:UIColorHex(B9B9B9) titleFont:[UIFont systemFontOfSize:12] space:0 backgroundColor:nil target:self action:@selector(lookMoreShitou:)];
//        [view addSubview:btn];
//        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, btn.bottom, self.view.width, 10)];
//        lineView.backgroundColor = kSeparatorColor;
//        [view addSubview:lineView];
//        return view;
//
//    } else
    if ([dic[cellTye] integerValue] == cellTypeWithImages) {
        if (self.imageIsOpen) {
            return [UIView new];
        }
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
        UIButton *btn = [UIButton createButtonWithFrame:CGRectMake(0, 0, 100, view.height) image:[UIImage imageNamed:@"down_arrow"] title:@"查看更多" titleColor:UIColorHex(666666) titleFont:[UIFont systemFontOfSize:13] space:0 backgroundColor:nil target:self action:@selector(lookMoreImages:)];
        btn.center = view.center;
        btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [view addSubview:btn];
        return view;
    }
    
    return [UIView new];
}

//// 根据托找个钻
//- (void)clickFindZuanBtn
//{
//    TTMessageViewController *messageVC = [[TTMessageViewController alloc] init];
//    messageVC.defaultSelectIndex = 1;
//    [self.navigationController pushViewController:messageVC animated:YES];
//}
//
//// 展开更多石头
//- (void)lookMoreShitou:(UIButton *)sender
//{
//    self.showAllShitou = YES;
//    [self.tableView reloadData];
//}

// 查看更多图片
- (void)lookMoreImages:(UIButton *)sender
{
    self.imageIsOpen = YES;
    [self.tableView reloadData];
}

// 点击裸石选择按钮
//- (void)clickSelectLuoshiButtonWithDiamondViewCell:(TTDiamondViewCell *)cell button:(UIButton *)button model:(TTDiamondModel *)model
//{
//    if (model.isSelect) {
//        if (![self.selectLuoshiArray containsObject:model]) {
//            [self.selectLuoshiArray addObject:model];
//        }
//    } else {
//        [self.selectLuoshiArray removeObject:model];
//    }
//}
//
//// 查看证书
//- (void)clickVerifyBtnWithDiamondViewCell:(TTDiamondViewCell *)cell certificateUrlString:(NSString *)urlString
//{
//    [TTLoginSingle lookCertificateWithUrlString:urlString];
//
//}
//
/////查看规格指南
//- (void)lookChicunGuide
//{
//    TTSizeGuideViewController *guideVC = [[TTSizeGuideViewController alloc] init];
//    [self.navigationController pushViewController:guideVC animated:YES];
//}

///分享
- (void)shareAction
{
    NSArray *array = @[@"分享商品图片", @"分享链接到朋友圈", @"分享链接给好友"];
    TTDianpuShareView *shareView = [TTDianpuShareView shareViewWithTitles:array selectBlock:^(NSInteger index) {
        if (index == 0) {
            TTDetailShareViewController *shareVC = [[TTDetailShareViewController alloc] initWithDetailModel:self.model];
            [self.navigationController pushViewController:shareVC animated:YES];
        } else if (index == 1) {
            [self shareToWeixinWithType:WXSceneTimeline];
        } else {
            [self shareToWeixinWithType:WXSceneSession];
        }
    }];
    [LLAnimationAlertView animationAlertViewWithView:shareView animationType:AnimationFromBottom];
}

- (void)shareToWeixinWithType:(int)type
{
    if (![WXApi isWXAppInstalled]) {
        [[UIApplication sharedApplication].keyWindow makeToast:@"未安装微信"];
        return;
    }
    WXWebpageObject *ext = [WXWebpageObject object];
    if (self.model.Share.ShareUrl > 0) {
        ext.webpageUrl = self.model.Share.ShareUrl;
    }
    
    NSURL *url = [NSURL URLWithString:self.model.Share.ShareImg ? : @""];
    NSData *imageData = [NSData dataWithContentsOfURL:url];
    // 压缩缩略图，大于64K不能分享
    UIImage *image = [UIImage imageWithData:imageData];
    UIImage *resultImage = [image zipImageWithSize:CGSizeMake(180, 180)];
    NSData *resultData = UIImageJPEGRepresentation(resultImage, 0.7);
    
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = self.model.Share.ShareTitle;
    message.description = self.model.Share.ShareDescription;
    [message setThumbData:resultData];
    message.mediaObject = ext;
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = type;
    
    [WXApi sendReq:req completion:^(BOOL success) {
        NSString *str = success ? @"分享成功" : @"分享失败";
        [[UIApplication sharedApplication].keyWindow makeToast:str];
    }];
}

//- (void)lookMoreInfo:(UIButton *)sender
//{
//    sender.selected = !sender.selected;
//    self.isOpen = sender.selected;
//    [self.tableView reloadSection:0 withRowAnimation:UITableViewRowAnimationFade];
//}
//
//- (void)clickMoreKuCunBtn:(UIButton *)sender
//{
//    self.isClickDingzhi = sender.tag == dingzhiTag;
//
//    self.presentFilterViewAction = PresentFilterViewActionDefault;
//
//    if (self.canShowGuigeArray.count == 0 && !self.isClickDingzhi) {
//        [self.view makeToast:@"暂无更多库存" duration:1.0 position:CSToastPositionCenter];
//        return;
//    }
//    [self presentFilterViewController];
//}
//
//- (void)presentFilterViewController
//{
//    //    for (TTDetailStockListModel *listModel in self.guigeArray) {
//    //        listModel.isClick = YES;
//    //    }
//    TTBaseDetailFilterViewController *filterVC;
//    filterVC = [self.model.CategoryName isEqualToString:@"对戒"] ? [[TTPairDetailFilterViewController alloc] init] : [[TTDetailFilterViewController alloc] init];
//    filterVC.transitioningDelegate = self.transition;
//    filterVC.modalPresentationStyle = UIModalPresentationCustom;
//    filterVC.selectDZ = self.isClickDingzhi;
//    self.isClickDingzhi = NO;
//    filterVC.styleLibraryId = self.styleLibraryId;
//    filterVC.xianhuoOtherParams = self.otherParams;
//    filterVC.detailVC = self;
//    filterVC.allShopShow = self.lookAllGuigeData;
//    [filterVC setModel:self.model datasArray:self.canShowGuigeArray selectArray:self.guigeArray customCount:self.model.CustomizedCount stockFilterCount:self.model.StockFilterCount];
//    @weakify(self)
//    filterVC.selectCompleteBlock = ^(NSArray * _Nonnull selectArray) {
//        @strongify(self)
//        [self.guigeArray removeAllObjects];
//        [self.guigeArray addObjectsFromArray:selectArray];
//
//        // 清除选中的裸石
//        [self.selectLuoshiArray removeAllObjects];
//
//        if (self.presentFilterViewAction == PresentFilterViewActionWithAddCart) {
//            // 加入购物车
//            [self addCartBtnClick];
//        } else if (self.presentFilterViewAction == PresentFilterViewActionWithBuy) {
//            // 购买
//            [self buyBtnClick];
//        }
//
//        //TODO: 请求裸石数据
//        BOOL shouldLoadLuoshiData = NO;
//        for (TTDetailStockListModel *mm in self.guigeArray) {
//            if (!mm.FinishedProduct) {
//                shouldLoadLuoshiData = YES;
//                break;
//            }
//        }
//        if (shouldLoadLuoshiData) {
//            [self afterSelectStyleGetLuoShiData];
//        } else {
//            [self removeLuoshiListData];
//        }
//
//        [self.tableView reloadData];
//    };
//    [self presentViewController:filterVC animated:YES completion:nil];
//}
//
//// 清除裸石列表数据，不展示了
//- (void)removeLuoshiListData
//{
//    for (int i = 0; i < self.dataArray.count; i++) {
//        NSDictionary *dic = self.dataArray[i];
//        if ([dic[cellTye] integerValue] == cellTypeWithShiTou) {
//            [self.dataArray removeObject:dic];
//            break;
//        }
//    }
//    [self.canShowShitouArray removeAllObjects];
//}
//
//- (void)afterSelectStyleGetLuoShiData
//{
//    // 如果没有选中
//    if (self.guigeArray.count == 0) {
//        [self removeLuoshiListData];
//        [self.tableView reloadData];
//        return;
//    }
//
//    // 是否有空托，如果有，就请求，如果没有，就删除裸石列表
//    BOOL hasNotFinished = NO;
//    for (TTDetailStockListModel *lm in self.guigeArray) {
//        if (!lm.FinishedProduct) {
//            hasNotFinished = YES;
//            break;
//        }
//    }
//    // 没有空托
//    if (!hasNotFinished) {
//        [self removeLuoshiListData];
//        [self.tableView reloadData];
//        return;
//    }
//
//    // 裸石加载过程菊花页面
//    self.loadingShitouView.hidden = self.canShowShitouArray.count == 0;
//    CGFloat h = self.canShowShitouArray.count * 85;
//    CGRect rect = [self.guigeFooterLabel convertRect:self.guigeFooterLabel.bounds toView:self.tableView];
//    self.loadingShitouView.frame = CGRectMake(0, CGRectGetMaxY(rect) + 90, self.view.width, h);
//
//    [MBProgressHUD showLoadingAnimationOnView:self.loadingShitouView];
//    co_launch(^{
//
//        NSArray *arr = await([self getLuoshiData]);
//
//        self.loadingShitouView.hidden = YES;
//
//        // 购物车中的数据
//        NSArray *cartCodeArray = [TTLoginSingle sharedSingle].cartCodeArray;
//        // 过滤掉购物车中存在的裸石
//        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT(cert_supplierNo in %@.StockBarCode)", cartCodeArray];
//        NSArray *canShowShitouArray = [arr filteredArrayUsingPredicate:predicate];
//        [self.canShowShitouArray removeAllObjects];
//        [self.canShowShitouArray addObjectsFromArray:canShowShitouArray];
//
//        // 如果开始不存在裸石列表，就插入
//        BOOL hasLuoshi = NO;
//        for (int i = 0; i < self.dataArray.count; i++) {
//            NSDictionary *dic = self.dataArray[i];
//            if ([dic[cellTye] integerValue] == cellTypeWithShiTou) {
//                hasLuoshi = YES;
//                break;
//            }
//        }
//        if (!hasLuoshi) {
//            [self.dataArray insertObject:@{cellTye : @(cellTypeWithShiTou), data : self.canShowShitouArray} atIndex:2];
//        }
//
//        [MBProgressHUD dismissAnimationOnView:self.loadingShitouView];
//
//        [self.tableView reloadData];
//
//    });
//}

- (COPromise *)getDetailData
{
    COPromise *promise = [COPromise promise];
    
    NSString *isOldUser = [TTLoginSingle sharedSingle].userModel.IsOldUser ? @"true" : @"false";
    
    NSDictionary *dic = @{
        @"param.styleLibraryId" : self.styleLibraryId,
        @"param.finishedProduct" : @(0),
        @"param.isOldUser" : isOldUser
    };
    
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getDetail_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [promise fulfill:[TTDetailModel modelWithJSON:responseObject]];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [promise fulfill:nil];
        
    } showLoadingInView:nil];
    
    return promise;
}

// 查询现货数据
- (COPromise *)getXianhuoDatas
{
    COPromise *promise = [COPromise promise];
    
    NSString *isOldUser = [TTLoginSingle sharedSingle].userModel.IsOldUser ? @"true" : @"false";
    
    NSDictionary *dic = @{
        @"param.styleLibraryId" : self.styleLibraryId,
        @"param.finishedProduct" : @(0),
        @"param.isOldUser" : isOldUser
    };
    NSMutableDictionary *mDic = dic.mutableCopy;
    if (self.otherParams) {
        [mDic addEntriesFromDictionary:self.otherParams];
    }
    //如果是显示所有数据使用dic
    NSDictionary *parmasDic = self.lookAllGuigeData ? dic : mDic;
    
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getXianhuo_api parameters:parmasDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        [promise fulfill:[TTXianhuoModel modelWithJSON:responseObject]];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [promise fulfill:nil];
        
    } showLoadingInView:nil];
    
    return promise;
}

///查询定制货品
- (COPromise *)getCustomDatas
{
    COPromise *promise = [COPromise promise];
    
    TTFactoryGradeModel *fgModel = self.model.Customized.FactoryGrade.firstObject;
    NSMutableDictionary *paramsDic = [NSMutableDictionary dictionary];
    [paramsDic setObject:@(1) forKey:@"param.pageIndex"];
    [paramsDic setObject:@(1) forKey:@"param.pageSize"];
    [paramsDic setObject:self.styleLibraryId forKey:@"param.styleLibraryId"];
    [paramsDic setObject:@(fgModel.ButtonValue) forKey:@"param.goodsGrade"];
    
    [[LLNetworkManagerTool sharedManager] postUrlString:getCustomList_api parameters:paramsDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSArray *arr = responseObject;
        TTDetailStockListModel *model = [TTDetailStockListModel modelWithJSON:arr.firstObject];
        model.buyCount = model.BuyNumberMin;
        [promise fulfill:model];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        [promise fulfill:nil];
        
    } showLoadingInView:nil];
    
    return promise;
}

// 查询裸石数据
//- (COPromise *)getLuoshiData
//{
//    COPromise *promise = [COPromise promise];
//
//    if (self.guigeArray.count == 0) {
//        [promise fulfill:nil];
//        return promise;
//    }
//
//    NSMutableArray *paramsArr = [NSMutableArray array];
//    for (TTDetailStockListModel *dM in self.guigeArray) {
//        if (![paramsArr containsObject:dM.InsertSizeRang]) {
//            if (dM.InsertSizeRang.length > 0) {
//                [paramsArr addObject:dM.InsertSizeRang];
//            }
//        }
//    }
//    NSString *strInsizeRange = [paramsArr componentsJoinedByString:@","];
//
//    NSDictionary *dic = @{
//        @"param.shape" : self.model.MStoneMosaicShape,
//        @"param.color" : self.model.Colour,
//        @"param.clarity" : self.model.Clarity,
//        @"param.cut" : self.model.Cut,
//        @"param.cert" : self.model.Cert,
//        @"param.polish" : self.model.Polish,
//        @"param.sym" : self.model.Sym,
//        @"param.flour" : self.model.Flour,
//        @"param.eyeClean" : self.model.EyeClean,
//        @"param.milky" : self.model.Milky,
//        @"param.browness" : self.model.Browness,
//        @"param.strInsizeRange" : strInsizeRange,
//        @"pagenum" : @(0),
//        @"pagesize" : @(10)
//    };
//    @weakify(self)
//    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:diamondDataSearchWholesaler_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        @strongify(self)
//        NSMutableArray *arr = [NSMutableArray array];
//        for (NSDictionary *dic in responseObject[@"data"]) {
//            TTDiamondModel *model = [TTDiamondModel modelWithJSON:dic];
//            model.cert_supplierNo = [NSString stringWithFormat:@"%@_%@", model.CertNo, model.SupplierNo];
//            [arr addObject:model];
//        }
//        // 裸石个数
////        self.diamondCount = [responseObject[@"count"] intValue];
//
//        [promise fulfill:arr];
//
//    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
//
//        [promise fulfill:nil];
//
//    } showLoadingInView:nil];
//
//
//    return promise;
//}

// 相似商品
- (COPromise *)getSimilarGoods
{
    COPromise *promise = [COPromise promise];
    NSDictionary *dic = @{
        @"param.styleLibraryId" : self.styleLibraryId
    };
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:similarGoods_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSMutableArray *arr = [NSMutableArray array];
        for (NSDictionary *mDic in responseObject[@"Data"]) {
            TTHomeListModel *model = [TTHomeListModel modelWithJSON:mDic];
            [arr addObject:model];
        }
        
        [promise fulfill:arr];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        [promise fulfill:nil];
    } showLoadingInView:nil];
    
    return promise;
}

// 购物车商品条码
- (COPromise *)getShopCartCodeData
{
    COPromise *promise = [COPromise promise];
    @weakify(self)
    [TTCommonNetData getShopCartCodeInfoSuccess:^(NSArray * _Nonnull cartCodeArray, int shopCount) {
        @strongify(self)
        
        self.shopCartView.count = shopCount;
        
        [promise fulfill:cartCodeArray];
        
    } failure:^{
        
        [promise fulfill:@[]];
    }];
    
    return promise;
}

///是否收藏了
- (void)getUserIsCollectionShop
{
    NSDictionary *dic = @{@"param.styleLibraryId" : self.styleLibraryId};
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:checkUserIsCollection_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        BOOL result = [responseObject boolValue];
        [self.headerView setIsCollection:result];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:nil];
}

- (void)getNetworkDatas
{
    [self getNetworkDataSuccessBlock:nil];
}

/// 添加图片
- (void)addImagesWithArray:(NSArray *)array
{
    if (array.count == 0) return;
    
    NSMutableArray *images = [NSMutableArray array];
    for (NSString *imageUrlStr in array) {
        TTDetailImageModel *imageModel = [[TTDetailImageModel alloc] init];
        imageModel.imageUrlStr = imageUrlStr;
        imageModel.imageHeight = self.view.width;   // 默认高度
        [images addObject:imageModel];
    }
    // 添加本地图片
    UIImage *image1 = [UIImage imageNamed:@"dianmian1"];
    TTDetailImageModel *imageModel = [[TTDetailImageModel alloc] init];
    imageModel.image = image1;
    imageModel.imageName = @"dianmian1";
    imageModel.imageHeight = image1.size.height * (self.view.width - 6) / image1.size.width;
    UIImage *image2 = [UIImage imageNamed:@"dianmian2"];
    TTDetailImageModel *imageModel2 = [[TTDetailImageModel alloc] init];
    imageModel2.image = image2;
    imageModel2.imageName = @"dianmian2";
    imageModel2.imageHeight = image2.size.height * (self.view.width - 6) / image2.size.width;
    [images addObject:imageModel];
    [images addObject:imageModel2];
    
    [self.dataArray addObject:@{cellTye : @(cellTypeWithImages), data : images}];
    
}

- (void)getNetworkDataSuccessBlock:(void (^)(TTDetailModel * _Nonnull, NSArray * _Nonnull, NSArray * _Nonnull, NSInteger, int))successBlock
{
    [self.dataArray removeAllObjects];
    
    
//    [self.indicatorView startAnimating];
//
    
    co_launch(^{
        
        self.model = await([self getDetailData]);
        
        
        
//        [self.dataArray insertObject:@{cellTye : @(cellTypeWithInfo), data : @[]} atIndex:0];
//
//        [self.dataArray insertObject:@{cellTye : @(cellTypeWithGuiGe), data : @[]} atIndex:1];
//
//        // 1、详细信息数据
//        [self setupDetailInfoArrayWithModel:self.model];
        
       
        
        // 2、已选规格
//        [self.canShowGuigeArray removeAllObjects];
//        if (self.model.StockNumber.intValue > 0) {
//            self.xianhuoModel = await([self getXianhuoDatas]);
//
//            self.model.StockList = self.xianhuoModel.StockList;
//            self.model.InsertSizeList = self.xianhuoModel.InsertSizeList;
//            self.model.HandSizeList = self.xianhuoModel.HandSizeList;
//            self.model.BraceletSizeList = self.xianhuoModel.BraceletSizeList;
//            self.model.GoldColorList = self.xianhuoModel.GoldColorList;
//            self.model.ProductColorList = self.xianhuoModel.ProductColorList;
//            self.model.FinishedProductList = self.xianhuoModel.FinishedProductList;
//            self.model.ProductGradeList = self.xianhuoModel.ProductGradeList;
//
//            [self.canShowGuigeArray addObjectsFromArray:self.xianhuoModel.StockList];
//
//        } else if (self.model.CustomizedCount > 0) {
//            TTDetailStockListModel *dslModel = await([self getCustomDatas]);
//            if (dslModel) {
//                [self.canShowGuigeArray addObject:dslModel];
//            }
//        }
//
//        // 2、规格数据: 取出默认选中的那个
//        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.IsSelect == YES"];
//        NSArray *result = [self.canShowGuigeArray filteredArrayUsingPredicate:predicate];
//
//        [self.guigeArray removeAllObjects];
//        if (result.count == 0 && self.canShowGuigeArray.count > 0) {
//            // 如果没有选中的，就显示数组的第一个
//            TTDetailStockListModel *firstModel = self.canShowGuigeArray.firstObject;
//            [self.guigeArray addObject:firstModel];
//        } else {
//            [self.guigeArray addObjectsFromArray:result];
//        }
//
//        [self.dataArray replaceObjectAtIndex:1 withObject:@{cellTye : @(cellTypeWithGuiGe), data : self.guigeArray}];
//        [self.tableView reloadSection:1 withRowAnimation:UITableViewRowAnimationFade];
//
//        [self.indicatorView stopAnimating];
//
//        // 3、推荐的石头
//        // 1.2 购物车商品条码，筛选出购物车中不包含的数据
//        NSArray *cartCodeArray = await([self getShopCartCodeData]);
//
//        TTDetailStockListModel *selectGGModel = self.guigeArray.firstObject;
//        if (!selectGGModel.FinishedProduct && self.guigeArray.count > 0) {
//            NSArray *arr = await([self getLuoshiData]);
//            // 过滤掉购物车中存在的裸石
//            NSPredicate *predicate2 = [NSPredicate predicateWithFormat:@"NOT(cert_supplierNo in %@.StockBarCode)", cartCodeArray];
//            NSArray *canShowShitouArray = [arr filteredArrayUsingPredicate:predicate2];
//            [self.canShowShitouArray removeAllObjects];
//            [self.canShowShitouArray addObjectsFromArray:canShowShitouArray];
//
//            [self.dataArray insertObject:@{cellTye : @(cellTypeWithShiTou), data : self.canShowShitouArray} atIndex:2];
//            [self.tableView insertSection:2 withRowAnimation:UITableViewRowAnimationFade];
//        }
        
        // 4、相似商品
        NSArray *similarArr = await([self getSimilarGoods]);
//        if (similarArr.count > 0) {
//            NSInteger index = self.homeModel.Share ? self.dataArray.count - 1 : self.dataArray.count;
//            [self.dataArray insertObject:@{cellTye : @(cellTypeWithSimilar), data : similarArr} atIndex:index];
//            [self.tableView insertSection:index withRowAnimation:UITableViewRowAnimationFade];
//        }
        
        // 0、头视图 headerView
        [self.headerView setModel:self.model similarArr:similarArr styleLibraryId:self.styleLibraryId isCollection:self.model.IsCollection];
        
        // 7、
        [self setupFooterView];
        
        [self setupBottomView];
        
        [self.tableView reloadData];
        
        // 5、图片
        if (self.model.DetailImg.count > 0) {
            if (self.homeModel == nil) {
                [self addImagesWithArray:self.model.DetailImg];
                [self.tableView insertSection:self.dataArray.count - 1 withRowAnimation:UITableViewRowAnimationFade];
            } else if (self.homeModel.Share == nil || self.homeModel.CustomizedFilterCondition == nil) {
                [self addImagesWithArray:self.model.DetailImg];
                [self.tableView insertSection:self.dataArray.count - 1 withRowAnimation:UITableViewRowAnimationFade];
            }
        }
        
        if (self.homeModel == nil) {
            [MBProgressHUD dismissAnimationOnView:self.view];
        }
        
        self.addCartBtn.enabled = YES;
        self.buyBtn.enabled = YES;
        
//        if (successBlock) {
//            successBlock(self.model, self.canShowGuigeArray, self.guigeArray, self.model.CustomizedCount, self.model.StockFilterCount);
//        }
        
        
        // 是否收藏了
        [self getUserIsCollectionShop];
        
        
    });
    
    // 5、图片
    [self addImagesWithArray:self.model.DetailImg];
    
    
    
    
    [self.tableView reloadData];
    
    
    
    // 定制条件
//    [self getCustomConditionDataSuccess:nil];
    
    
}

///// 获取款式定制条件
//- (void)getCustomConditionDataSuccess:(nullable dispatch_block_t)success
//{
//    if (self.customConditionModel) {
//        if (success) {
//            success();
//        }
//        return;
//    }
//    NSDictionary *dic = @{
//        @"param.styleLibraryId" : self.styleLibraryId
//    };
//    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getCustomCondition_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//
//        self.customConditionModel = [TTCustomConditionModel modelWithJSON:responseObject];
//
//        if (success) {
//            success();
//        }
//
//    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
//
//        if (success) {
//            success();
//        }
//
//    } showLoadingInView:nil];
//}


//- (void)setupDetailInfoArrayWithModel:(TTDetailModel *)model
//{
//    NSMutableArray *arr = [NSMutableArray array];
//    //    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"款式分类: " leftContent:self.model.CategoryName rightTitle:@"性       别: " rightContent:self.model.Gender]];
//    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"成       色: " leftContent:model.GoldColor rightTitle:@"货       品: " rightContent:model.FinishedProduct]];
//    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"工       费: " leftContent:model.WorkTotalPrice rightTitle:@"损       耗: " rightContent:model.GoldLoss]];
//    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"款式镶法: " leftContent:model.StyleSettingName rightTitle:@"爪数/叶数: " rightContent:model.ClawNumber]];
//    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"加工工艺: " leftContent:model.Technology rightTitle:@"款式风格: " rightContent:model.LargeStyles]];
//    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"颈部造型: " leftContent:model.NeckModeling rightTitle:@"颈部花头: " rightContent:model.NeckFlower]];
//    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"款式爪型: " leftContent:model.Alias rightTitle:@"款式戒臂: " rightContent:model.StyleArm]];
//    //    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"主       石: " leftContent:self.model.MStoneNumber rightTitle:@"主石重量: " rightContent:self.model.MStoneWeight]];
//    //    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"副石数量: " leftContent:self.model.VStoneWeight rightTitle:@"" rightContent:@""]];
//    // model.ProductServer
//    [arr addObject:[self createDetailInfoDicWithLeftTitle:@"产品服务: " leftContent:@"出售商品提供专柜验货、全国联保" rightTitle:@"" rightContent:@""]];
//
//    [self.dataArray replaceObjectAtIndex:0 withObject:@{cellTye : @(cellTypeWithInfo), data : arr}];
//}
//
//- (NSDictionary *)createDetailInfoDicWithLeftTitle:(NSString *)leftTitle leftContent:(NSString *)leftContent rightTitle:(NSString *)rightTitle rightContent:(NSString *)rightContent
//{
//
//    return @{
//        @"leftTitle" : leftTitle,
//        @"leftContent" : leftContent,
//        @"rightTitle" : rightTitle,
//        @"rightContent" : rightContent
//    };
//}

// 底部footer
- (void)setupFooterView
{
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 100)];
    footerView.backgroundColor = [UIColor whiteColor];
    
    UILabel *oneTitleLabel = [UILabel labelWithTitle:@"价格提示" color:UIColorHex(333333) font:[UIFont systemFontOfSize:15]];
    [footerView addSubview:oneTitleLabel];
    [oneTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(10);
        make.left.mas_equalTo(10);
    }];
    NSString *oneStr = @"通过APP明示的注册方式或直接到淘托线下服务门店注册的方式即可成为会员。";
    UILabel *oneLabel = [UILabel labelWithTitle:oneStr color:UIColorHex(999999) fontSize:12];
    oneLabel.numberOfLines = 0;
    [footerView addSubview:oneLabel];
    [oneLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(oneTitleLabel.mas_bottom).mas_offset(5);
        make.left.mas_equalTo(22);
        make.right.equalTo(footerView).mas_offset(-10);
    }];
    
    UIButton *twoTitleBtn = [self createButtonWithTitle:@"划线价格: "];
    [footerView addSubview:twoTitleBtn];
    [twoTitleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(oneLabel.mas_bottom).mas_offset(15);
        make.left.equalTo(oneTitleLabel);
    }];
    NSString *twoStr = @"划线价格可能是商品的专柜价、吊牌价或正品的零售价、指导价、或该商品是淘托线下门店向非会员展示的销售价，并非原价，仅供您参考。";
    UILabel *twoLabel = [UILabel labelWithTitle:twoStr color:UIColorHex(999999) fontSize:12];
    twoLabel.numberOfLines = 0;
    [footerView addSubview:twoLabel];
    [twoLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(twoTitleBtn.mas_bottom);
        make.left.mas_equalTo(oneLabel);
        make.right.equalTo(footerView).mas_offset(-10);
    }];
    
    UIButton *threeTitleBtn = [self createButtonWithTitle:@"未划线价格: "];
    [footerView addSubview:threeTitleBtn];
    [threeTitleBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(twoLabel.mas_bottom).mas_offset(15);
        make.left.equalTo(oneTitleLabel);
    }];
    
    NSString *threeStr = @"未划线价格是商品在淘托对会员展示的销售价、具体的成交价可能会因为会员使用了优惠券积分等而发送变化，最终以订单结算页价格为准。";
    UILabel *threeLabel = [UILabel labelWithTitle:threeStr color:UIColorHex(999999) fontSize:12];
    threeLabel.numberOfLines = 0;
    [footerView addSubview:threeLabel];
    [threeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(threeTitleBtn.mas_bottom);
        make.left.mas_equalTo(oneLabel);
        make.right.equalTo(footerView).mas_offset(-10);
    }];
    
    UIImageView *dotImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"xiaoyuandian"]];
    dotImageView.contentMode = UIViewContentModeCenter;
    [footerView addSubview:dotImageView];
    [dotImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(threeLabel.mas_bottom).mas_offset(15);
        make.width.height.mas_equalTo(15);
        make.left.equalTo(oneTitleLabel);
    }];
    NSString *fourStr = @"此说明仅当价格比较时有效，若淘托线下服务门店单独对划线价进行说明的，以门店的表述为准";
    UILabel *fourLabel = [UILabel labelWithTitle:fourStr color:UIColorHex(999999) fontSize:12];
    fourLabel.numberOfLines = 0;
    [footerView addSubview:fourLabel];
    [fourLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(dotImageView);
        make.left.equalTo(oneLabel);
        make.right.equalTo(footerView).mas_offset(-10);
    }];
    
    UILabel *fiveTitleLabel = [UILabel labelWithTitle:@"免责说明" color:UIColorHex(333333) font:[UIFont systemFontOfSize:15]];
    [footerView addSubview:fiveTitleLabel];
    [fiveTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fourLabel.mas_bottom).mas_offset(10);
        make.left.equalTo(oneTitleLabel);
        make.right.equalTo(footerView).mas_offset(-10);
    }];
    NSString *fiveStr = @"淘托APP商品款式图片部分搜集于互联网，或第三方用户提供，如果该款式有侵犯您的品牌权益，请联系我们删除。";
    UILabel *fiveLabel = [UILabel labelWithTitle:fiveStr color:UIColorHex(999999) fontSize:12];
    fiveLabel.numberOfLines = 0;
    [footerView addSubview:fiveLabel];
    [fiveLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(fiveTitleLabel.mas_bottom).mas_offset(5);
        make.left.mas_equalTo(22);
        make.right.equalTo(footerView).mas_offset(-10);
    }];
    
    [footerView layoutIfNeeded];
    
    footerView.height = fiveLabel.bottom + 30;
    
    self.tableView.tableFooterView = footerView;
}

- (UIButton *)createButtonWithTitle:(NSString *)title
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"xiaoyuandian"] forState:UIControlStateNormal];
    [btn setTitle:title forState:UIControlStateNormal];
    [btn setTitleColor:UIColorHex(666666) forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13];
    btn.titleLabel.numberOfLines = 0;
    btn.imageView.contentMode = UIViewContentModeCenter;
    return btn;
}

- (BOOL)canAddCartOrBuy
{
    BOOL canAdd = YES;
//    if (self.guigeArray.count == 0) {
////        [self presentFilterViewController];
//        return NO;
//    }
//
//    for (TTDetailStockListModel *model in self.guigeArray) {
//        if (!model.selected) {
//            canAdd = NO;
//            break;
//        }
//    }
//    // 如果没有选中的规格数据，并且规格区有列表数据
//    if (!canAdd) {
//        if (self.selectLuoshiArray.count > 0) {
//            // 有选中的裸石，就把规格的这个数据也带过去购买或加入购物车
//            return YES;
//        } else {
//            // 也有选中裸石
////            [self presentFilterViewController];
//        }
//
//    }
    return canAdd;
}

/// 查看现货
- (void)showExistView
{
    
    
    self.existChooseView = [[TTExistGoodsChooseView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height * 0.9)];
    self.existChooseView.detailModel = self.model;
    self.existChooseView.styleLibraryId = self.styleLibraryId;
    [self.existChooseView showInView:self.view];
    
    @weakify(self)
    self.existChooseView.addShopCartSuccess = ^{
        @strongify(self)
        self.shopCartView.count = [TTLoginSingle sharedSingle].shopCartCount;
    };
    
    [self.tableView setContentOffset:CGPointMake(0, -kStatusBarHeight) animated:NO];
}


// 加入购物车
- (void)addCartBtnClick
{
    [self showExistView];
    
//    self.presentFilterViewAction = PresentFilterViewActionWithAddCart;
//    if (![self canAddCartOrBuy]) return;
//
//    NSMutableArray *goodsArray = [NSMutableArray array];
//    NSMutableDictionary *goodDic = [NSMutableDictionary dictionary];
//    // 1. 规格数据
////    for (TTDetailStockListModel *listModel in self.guigeArray) {
////        listModel.selected = YES;
////        NSDictionary *dic = @{
////            @"GoodsType": @(listModel.StockType),
////            @"GoodsTitle": self.model.GoodsTitle,
////            @"GoodsImage": self.model.CoverMapImg,
////            @"GoodsBarCode": listModel.GoodsBarCode,
////            @"AddPrice": listModel.Price,
////            @"StyleLibraryId": self.styleLibraryId,
////            @"CategoryName": self.model.CategoryName,
////            @"InsertSize": listModel.InsertSize1,
////            @"Number": @(listModel.buyCount == 0 ? 1 : listModel.buyCount),
////            @"CustomizedGoldColor" : listModel.GoldColor,
////            @"BuyNumberMax" : @(listModel.buyCount),
////            @"C_Cycle" : listModel.Cycle,
////            @"C_PriceDiffRang" : listModel.PriceDiffRang,
////            @"GoodsGrade" : listModel.ProductGrade,
////            @"Description" : listModel.GoodsAttr
////        };
////        [goodsArray addObject:dic];
////    }
////    // 2. 石头数据
////    for (TTDiamondModel *stModel in self.selectLuoshiArray) {
////        NSString *luoshiTitle = [NSString stringWithFormat:@"%@ %@ %@ %@ %@ %@ %@ %@", stModel.Shape, stModel.DiaSize, stModel.Color, stModel.Clarity, stModel.Cut, stModel.Sym, stModel.Polish, stModel.Flour];
////        CGFloat diaSize = stModel.DiaSize.floatValue * 100;
////        CGFloat insertSize = [TTLoginSingle findDiamondSizeWithSize:diaSize];
////        NSDictionary *dic = @{
////            @"GoodsType": @(1),
////            @"GoodsTitle": luoshiTitle,
////            @"GoodsImage": stModel.Shape,
////            @"GoodsBarCode": stModel.GoodsBarCode,
////            @"DiaRef": stModel.DiaRef,
////            @"SupplierNo": stModel.SupplierNo,
////            @"CertNo": stModel.CertNo,
////            @"AddPrice": stModel.Price,
////            @"StyleLibraryId": self.styleLibraryId,
////            @"CategoryName": self.model.CategoryName,
////            @"InsertSize": @(insertSize),
////            @"DiaSize" : stModel.DiaSize,
////            @"Number": @(1),
////            @"BuyNumberMax": @(1)
////        };
////        [goodsArray addObject:dic];
////    }
////    [goodDic setObject:goodsArray forKey:@"GoodsList"];
////
//    [MBProgressHUD showLoadingAnimationOnView:self.view];
//    @weakify(self)
//    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:addShopCart_api parameters:goodDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        @strongify(self)
//        [MBProgressHUD showSuccess:@"已加入购物车"];
////        // 1. 清除可展示的数据中加入购物车的数据
////        for (TTDetailStockListModel *model in self.guigeArray) {
////            [self.canShowGuigeArray removeObject:model];
////        }
////        // 2. 清除选中规格数据
////        [self.guigeArray removeAllObjects];
////        // 3. 取出 可展示的数据中 的 第一个元素展示出来
////        if (self.canShowGuigeArray.count == 0 && self.model.Customized.CustomizedInfoDefault) {
////            //定制商品
////            TTDetailStockListModel *dslModel = self.model.Customized.CustomizedInfoDefault;
////            dslModel.buyCount = dslModel.BuyNumberMin;
////            [self.canShowGuigeArray addObject:dslModel];
////        }
////        if (self.canShowGuigeArray.count > 0) {
////            TTDetailStockListModel *firstModel = self.canShowGuigeArray.firstObject;
////            //            firstModel.isClick = YES;
////            [self.guigeArray addObject:firstModel];
////        }
////
//        [TTCommonNetData handleShopCartCodeInfoWithArray:responseObject];
//
//        self.shopCartView.count = [TTLoginSingle sharedSingle].shopCartCount;
//
//        [MBProgressHUD dismissAnimationOnView:self.view];
//        // 4. 清除选中的裸石
////        [self.selectLuoshiArray removeAllObjects];
//        // 5. 请求裸石数据
////        [self afterSelectStyleGetLuoShiData];
//
//        // 通知购物车页面刷新
//        [[TTLoginSingle sharedSingle].shopCartSubject sendNext:@(1)];
//
//    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
//
//        [MBProgressHUD dismissAnimationOnView:self.view];
//
//    } showLoadingInView:nil];
//
    
}

// 立即购买
- (void)buyBtnClick
{
    
    [self showExistView];
    
//    self.presentFilterViewAction = PresentFilterViewActionWithBuy;
//
//    if (![self canAddCartOrBuy]) return;
//
//    // 1. 准备请求裸石的数据
//    TTDiamondsRecommendModel *model = [[TTDiamondsRecommendModel alloc] init];
//    model.Colour = self.model.Colour;
//    model.Clarity = self.model.Clarity;
//    model.Cut = self.model.Cut;
//    model.Polish = self.model.Polish;
//    model.Sym = self.model.Sym;
//    model.Cert = self.model.Cert;
//    model.Flour = self.model.Flour;
//    model.EyeClean = self.model.EyeClean;
//    model.Milky = self.model.Milky;
//    model.Browness = self.model.Browness;
//
//    NSMutableArray *array = [NSMutableArray array];
//    // 2. 选中的规格：self.guigeArray
//    for (TTDetailStockListModel *listModel in self.guigeArray) {
//        listModel.selected = YES;
//        TTShopCartSubDetailModel *dm = [[TTShopCartSubDetailModel alloc] init];
//        dm.GoodsBarCode = listModel.GoodsBarCode;
//        dm.GoodsType = listModel.StockType;
//        dm.GoodsTitle = self.model.GoodsTitle;
//        dm.GoodsImage = self.model.CoverMapImg;
//        dm.GoodsDescribe = listModel.GoodsAttr;
//        dm.GoodsPrice = listModel.Price;
//        dm.CertType = listModel.CertType;
//        dm.QueryCode = listModel.QueryCode;
//        dm.MStoneMosaicShape = self.model.MStoneMosaicShape;
//        dm.InsertSizeRang = listModel.InsertSizeRang;
//        dm.CategoryName = self.model.CategoryName;
//        dm.StyleLibraryId = self.styleLibraryId;
//        dm.InsertSize = listModel.InsertSize1;
//        dm.GoodsValuationPriceTypeText = listModel.GoodsValuationPriceTypeText;
//        dm.FinishedProduct = listModel.FinishedProduct;
//        dm.LocationName = listModel.LocationName;
//        dm.Status = self.model.StyleStatus;
//        dm.ProductGradeName = listModel.ProductGradeName;
//        dm.CustomizedGoldColor = listModel.GoldColor;
//        dm.StockTypeName = listModel.StockTypeName;
//        dm.FactoryLabel = listModel.FactoryLabel;
//        dm.Cycle = listModel.Cycle;
//        dm.Number = listModel.buyCount;
//        dm.ProductGrade = listModel.ProductGrade;
//
//        CGFloat cellImageH = 65 * kScale + 40;
//        NSString *content = [dm.GoodsDescribe componentsJoinedByString:@" "];
//        CGFloat contentH = [content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH - 145 * kScale - 10, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12]} context:nil].size.height + 5;
//        CGFloat sh = contentH + 35 + 35;
//        sh = sh > cellImageH ? sh : cellImageH;
//        dm.h = sh;
//        [array addObject:dm];
//    }
//
//    // 3. 选中的裸石：self.selectLuoshiArray
//    for (TTDiamondModel *diaModel in self.selectLuoshiArray) {
//        TTShopCartSubDetailModel *dm = [TTCommondDataModel diamondModelToShopCartSubDetailModelWithModel:diaModel];
//        dm.StyleLibraryId = self.styleLibraryId;
//        [array addObject:dm];
//    }
//
//    TTCommitOrderViewController *commitVC = [[TTCommitOrderViewController alloc] initWithShopArray:array diamondModel:model];
//    [self.navigationController pushViewController:commitVC animated:YES];
}


// 开始定制按钮点击
- (void)startCustomBtnClick
{
//    if (_customView) {
//        // TODO: 赋值
//        _customView.styleLibraryId = self.styleLibraryId;
//        _customView.customModel = self.customConditionModel;
//        [_customView show];
//        return;
//    }
    
//    @weakify(self)
//    [self getCustomConditionDataSuccess:^{
//        @strongify(self)
//        self.customView = [[LLScreenView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height*0.9)];
//        self.customView.customModel.CoverMapImg = self.model.CoverMapImg;
//        self.customView.styleLibraryId = self.styleLibraryId;
//        self.customView.customModel = self.customConditionModel;
//        [self.customView show];
//    }];
    
    
    [self.tableView setContentOffset:CGPointMake(0, -kStatusBarHeight) animated:NO];
    
    self.customView = [[LLScreenView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.view.height*0.9)];
    self.customView.CoverMapImg = self.model.CoverMapImg;
    self.customView.styleLibraryId = self.styleLibraryId;
    [self.customView showInView:self.view];
    
}

// 底部view
- (void)setupBottomView
{
//    if (self.bottomView) return;
    [self.view layoutIfNeeded];
    [_bottomView removeFromSuperview];
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.tableView.bottom, self.view.width, 50)];
    [self.view addSubview:_bottomView];
    
    [LLLineUtilies addLineInView:_bottomView startPoint:CGPointZero endPoint:CGPointMake(_bottomView.width, 0) lineColor:kSeparatorColor];
    
    CGFloat btnW = _bottomView.width * 0.15;
    @weakify(self)
    TTShopCartView *kefuView = [[TTShopCartView alloc] initWithFrame:CGRectMake(0, 2, btnW, 48) imageName:@"erji" title:@"客服" clickShopCartBlock:^(TTShopCartView *cartView) {
        @strongify(self)
        if (![TTLoginSingle sharedSingle].isLogin) {
            // 登录
            [self presentLoginViewController];
            return;
        }
        
        // 打电话
        [[TTLoginSingle sharedSingle].loginModel.SalesmanMobile callPhone];
        
    }];
    [_bottomView addSubview:kefuView];
    
    
    _shopCartView = [[TTShopCartView alloc] initWithFrame:CGRectMake(kefuView.right, kefuView.top, btnW, kefuView.height) imageName:@"shopcart" title:@"购物车" clickShopCartBlock:^(TTShopCartView *cartView) {
        @strongify(self)
        
        if (![TTLoginSingle sharedSingle].isLogin) {
            [self presentLoginViewController];
            return;
        }
        
        BOOL has = NO;
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[TTShopCartViewController class]]) {
                has = YES;
                [self.navigationController popToViewController:vc animated:YES];
                break;
            }
        }
        if (!has) {
            TTShopCartViewController *shopCartVC = [[TTShopCartViewController alloc] init];
            [self.navigationController pushViewController:shopCartVC animated:YES];
        }
        
    }];
    _shopCartView.count = [TTLoginSingle sharedSingle].shopCartCount;
    [_bottomView addSubview:_shopCartView];
    
    CGFloat rightBtnW = (_bottomView.width * 0.7 - 20) * 0.5;
    UIButton *addCartBtn = [UIButton createButtonWithTitle:@"加入购物车" titleColor:UIColorHex(#8B57E6) titleFontSize:14 borderColor:UIColorHex(#8B57E6) cornerRadius:20 contentEdgeInsets:UIEdgeInsetsZero target:self action:@selector(addCartBtnClick)];
    addCartBtn.isNeedLogin = YES;
    addCartBtn.frame = CGRectMake(_shopCartView.right, 5, rightBtnW, 40);
    [_bottomView addSubview:addCartBtn];
    self.addCartBtn = addCartBtn;
    
    UIButton *buyBtn = [UIButton createButtonWithTitle:@"立即购买" titleColor:UIColor.whiteColor titleFont:[UIFont systemFontOfSize:14] backgroundColor:UIColorHex(#8B57E6) cornerRadius:20 target:self action:@selector(buyBtnClick)];
    buyBtn.frame = CGRectMake(addCartBtn.right + 10, 5, rightBtnW, 40);
    buyBtn.isNeedLogin = YES;
    [_bottomView addSubview:buyBtn];
    self.buyBtn = buyBtn;
    
    self.addCartBtn.enabled = NO;
    self.buyBtn.enabled = NO;
    
    // 开始定制按钮
    UIButton *startCustomBtn = [UIButton createButtonWithTitle:@"开始定制" titleColor:UIColor.whiteColor titleFont:[UIFont systemFontOfSize:14] backgroundColor:UIColorHex(#8B57E6) cornerRadius:20 target:self action:@selector(startCustomBtnClick)];
    startCustomBtn.frame = CGRectMake(_shopCartView.right, 5, _bottomView.width*0.7-10, 40);
    [_bottomView addSubview:startCustomBtn];
    self.startCustomBtn = startCustomBtn;
    
    if (self.model.isExistingGoods) {
        // 现货
        self.addCartBtn.hidden = NO;
        self.buyBtn.hidden = NO;
        self.startCustomBtn.hidden = YES;
    }
    if (self.model.isCustomGoods) {
        // 定制
        self.addCartBtn.hidden = YES;
        self.buyBtn.hidden = YES;
        self.startCustomBtn.hidden = NO;
    }
    
    
    if (self.model.isSelloutGoods || self.model.StyleStatus.intValue == 0) {
        // 售罄 或 下架
        self.selloutView.hidden = NO;
    }
    
    
//    // 售罄
//    if (self.model.isSelloutGoods) {
//        UIButton *selloutBtn = [UIButton createButtonWithTitle:@"已售罄" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:15] backgroundColor:UIColorHex(999999) target:nil action:nil];
//        selloutBtn.frame = CGRectMake(addCartBtn.left, addCartBtn.top, addCartBtn.width + buyBtn.width, addCartBtn.height);
//        [_bottomView addSubview:selloutBtn];
//    }
//
//    // 下架
//    if (self.model.StyleStatus.intValue == 0) {
//
//        addCartBtn.backgroundColor = UIColorHex(999999);
//        buyBtn.backgroundColor = UIColorHex(999999);
//
//        addCartBtn.enabled = NO;
//        buyBtn.enabled = NO;
//
//        UILabel *xiajiaLabel = [UILabel labelTextCenterWithTitle:@"该商品已下架" color:[UIColor whiteColor] fontSize:11];
//        xiajiaLabel.backgroundColor = UIColorHex(DEDEDE);
//        xiajiaLabel.frame = CGRectMake(0, -25, self.view.width, 25);
//        [_bottomView addSubview:xiajiaLabel];
//    }
//
    
}

/// homeModel -> detailModel
- (void)homeModelToDetailModelWithHomeModel:(TTHomeListModel *)model
{
    self.model = [[TTDetailModel alloc] init];
    self.model.GoodsTitle = model.GoodsTitle;
    self.model.GoldColor = model.GoldColor;
    self.model.FinishedProduct = model.IsFinishedProduct;
    self.model.WorkTotalPrice = model.WorkTotalPrice;
    self.model.Technology = model.Technology;
    self.model.GoldLoss = model.GoldLoss;
    self.model.SalesVolume = model.SalesVolume;
    self.model.StyleArm = model.ClawType;
    self.model.StyleSettingName = model.StyleSettingName;
    self.model.Price = model.Price;
    self.model.StyleStatus = model.StyleSatus;
    self.model.BrowseNumber = model.BrowseNumber;
    self.model.StockNumber = model.StockCount;
    self.model.CustomizedCount = model.CustomizedCount;
    self.model.Customized = model.CustomizedFilterCondition;
    self.model.GoodsImageList = model.OtherGoodsImage;
    self.model.StyleLibraryLabels = model.StyleLibraryLabels;
    self.model.StandardNumber = model.StandardNumber;
    self.model.ClawNumber = model.ClawNumber;
    self.model.LargeStyles = model.LargeStyles;
    self.model.NeckFlower = model.NeckFlower;
    self.model.NeckModeling = model.NeckModeling;
    self.model.DetailImg = model.DetailImg;
    self.model.Share = model.Share;
    self.model.CoverMapImg = model.GoodsImage;
    self.model.CategoryName = model.CategoryName;
    
    self.model.RelationStandardNumber = self.homeModel.RelationStandardNumber;
    self.model.Gender = self.homeModel.Gender;
    
}


- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyImageName = @"tao_nodata";
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//        [_tableView registerClass:[TTDetailInfoViewCell class] forCellReuseIdentifier:detailInfoCellID];
//        [_tableView registerClass:[TTSpecificationViewCell class] forCellReuseIdentifier:detailSecificationCellID];
//        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTDiamondViewCell class]) bundle:nil] forCellReuseIdentifier:detailDiamondCellID];
//        [self.tableView registerClass:[TTHomeListTableViewCell class] forCellReuseIdentifier:detailSimilarCellID];
        [_tableView registerClass:[TTDetailImageViewCell class] forCellReuseIdentifier:detailImagesCellID];
        _tableView.tableFooterView = [UIView new];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop).mas_offset(-kStatusBarHeight);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-50);
        }];
    }
    return _tableView;
}

//- (UIView *)loadingShitouView
//{
//    if (!_loadingShitouView) {
//        _loadingShitouView = [[UIView alloc] init];
//        _loadingShitouView.hidden = YES;
//        [self.tableView addSubview:_loadingShitouView];
//    }
//    return _loadingShitouView;
//}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (TTDetailHeaderView *)headerView
{
    if (!_headerView) {
        _headerView = [TTDetailHeaderView headerViewWithDetailModel:nil];
        self.tableView.tableHeaderView = _headerView;
        ///观察屏幕是否可旋转
        [_headerView.subject subscribeNext:^(id  _Nullable x) {
            AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            delegate.allowRotate = [x boolValue];
        }];
    }
    return _headerView;
}

- (UIView *)navBarView
{
    if (!_navBarView) {
        _navBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, StatusBarAndNavBar_Height)];
        [self.view insertSubview:_navBarView aboveSubview:self.tableView];
        
        UIButton *backBtn = [UIButton createButtonWithImage:[UIImage imageNamed:@"detail_nav_back"] target:self action:@selector(backAction)];
        backBtn.imageView.contentMode = UIViewContentModeCenter;
        backBtn.frame = CGRectMake(5, kStatusBarHeight, 44, 44);
        [_navBarView addSubview:backBtn];
        
        UIButton *shareBtn = [UIButton createButtonWithImage:[UIImage imageNamed:@"detailshare"] target:self action:@selector(shareAction)];
        shareBtn.imageView.contentMode = UIViewContentModeCenter;
        shareBtn.frame = CGRectMake(self.view.width - 44, kStatusBarHeight, 44, 44);
        [_navBarView addSubview:shareBtn];
        
        
    }
    return _navBarView;
}


- (UIView *)selloutView
{
    if (!_selloutView) {
        _selloutView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _selloutView.backgroundColor = UIColor.whiteColor;
        [self.view addSubview:_selloutView];
        
        _selloutView.hidden = YES;
        
        UIButton *backBtn = [UIButton createButtonWithImage:[UIImage imageNamed:@"nav_back"] target:self action:@selector(backAction)];
        backBtn.frame = CGRectMake(0, kStatusBarHeight, 44, 44);
        [_selloutView addSubview:backBtn];
        
        UILabel *titleLabel = [UILabel labelWithTitle:@"商品详情" color:UIColor.blackColor font:[UIFont boldSystemFontOfSize:18] alignment:NSTextAlignmentCenter];
        titleLabel.frame = CGRectMake((self.view.width - 120) * 0.5, kStatusBarHeight, 120, 44);
        [_selloutView addSubview:titleLabel];
        
        UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"detail_goods_sellout"]];
        [_selloutView addSubview:imageView];
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(_selloutView);
        }];
        
        UILabel *selloutLabel = [UILabel labelWithTitle:@"商品已售罄" color:UIColorHex(#808080) fontSize:17];
        [_selloutView addSubview:selloutLabel];
        [selloutLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(imageView.mas_bottom).offset(50);
            make.centerX.equalTo(_selloutView);
        }];
        
    }
    return _selloutView;
}

//- (NSMutableArray *)guigeArray
//{
//    if (!_guigeArray) {
//        _guigeArray = [NSMutableArray array];
//    }
//    return _guigeArray;
//}
//
//- (NSMutableArray *)canShowGuigeArray
//{
//    if (!_canShowGuigeArray) {
//        _canShowGuigeArray = [NSMutableArray array];
//    }
//    return _canShowGuigeArray;
//}
//
//- (NSMutableArray *)canShowShitouArray
//{
//    if (!_canShowShitouArray) {
//        _canShowShitouArray = [NSMutableArray array];
//    }
//    return _canShowShitouArray;
//}
//
//- (NSMutableArray *)selectLuoshiArray
//{
//    if (!_selectLuoshiArray) {
//        _selectLuoshiArray = [NSMutableArray array];
//    }
//    return _selectLuoshiArray;
//}
//
//- (UIActivityIndicatorView *)indicatorView
//{
//    if (!_indicatorView) {
//        _indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
//    }
//    return _indicatorView;
//}

- (void)dealloc
{
    NSLog(@"[< %@ >] --> 释放了", self.className);
    if (self.headerView.playerView) {
        [self.headerView.playerView remoAllOberver];
    }
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


@end
